#!/usr/bin/env python
# Copyright (c) 2006-2008 Mitch Garnaat http://garnaat.org/
#
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish, dis-
# tribute, sublicense, and/or sell copies of the Software, and to permit
# persons to whom the Software is furnished to do so, subject to the fol-
# lowing conditions:
#
# The above copyright notice and this permission notice shall be included
# in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
# OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABIL-
# ITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT
# SHALL THE AUTHOR BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, 
# WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
# IN THE SOFTWARE.
import queuetools, os, signal, sys
import subprocess
import time
from optparse import OptionParser
from boto.mapreduce.partitiondb import PartitionDB, Partition, Version
from lqs import LQSServer, PersistHandler
from boto.exception import SDBPersistenceError
from boto.sdb.persist import get_manager, revive_object_from_id

USAGE = """
  SYNOPSIS
    %prog [options] [command]
  DESCRIPTION
    Delete a PartitionDB and all related data in SimpleDB and S3.
"""
class Client:

    def __init__(self, queue_name):
        self.q = queuetools.get_queue(queue_name)
        self.q.connect()
        self.manager = get_manager()
        self.process()

    def process(self):
        m = self.q.get()
        while m['item']:
            print 'Deleting: %s' % m['item']
            obj = revive_object_from_id(m['item'], manager=self.manager)
            obj.delete()
            self.q.delete(m)
            m = self.q.get()
        print 'client processing complete'

class Server:

    def __init__(self, pdb_name, domain_name=None):
        self.pdb_name = pdb_name
        self.manager = get_manager(domain_name)
        self.pdb = PartitionDB.get(name=self.pdb_name)
        self.serve()

    def serve(self):
        args = {'pdb_id' : self.pdb.id}
        rs = self.pdb.get_related_objects('pdb')
        self.pdb.delete()
        s = LQSServer('', PersistHandler, rs, args)
        s.serve_forever()
    
class Delete:

    Commands = {'client' : 'Start a Delete client',
                'server' : 'Start a Delete server'}

    def __init__(self):
        self.parser = OptionParser(usage=USAGE)
        self.parser.add_option("--help-commands", action="store_true", dest="help_commands",
                               help="provides help on the available commands")
        self.parser.add_option('-d', '--domain-name', action='store', type='string',
                               help='name of the SimpleDB domain where PDB objects are stored')
        self.parser.add_option('-n', '--num-processes', action='store', type='int', dest='num_processes',
                               help='the number of client processes launched')
        self.parser.set_defaults(num_processes=5)
        self.parser.add_option('-p', '--pdb-name', action='store', type='string',
                               help='name of the PDB in which to store files (will create if necessary)')
        self.options, self.args = self.parser.parse_args()
        self.prog_name = sys.argv[0]

    def print_command_help(self):
        print '\nCommands:'
        for key in self.Commands.keys():
            print '  %s\t\t%s' % (key, self.Commands[key])

    def do_server(self):
        if not self.options.pdb_name:
            self.parser.error('No PDB name provided')
        s = Server(self.options.pdb_name, self.options.domain_name)

    def do_client(self):
        c = Client('localhost')
        
    def main(self):
        if self.options.help_commands:
            self.print_command_help()
            sys.exit(0)
        if len(self.args) == 0:
            if not self.options.pdb_name:
                self.parser.error('No PDB name provided')
            server_command = '%s -p %s ' % (self.prog_name, self.options.pdb_name)
            server_command += ' server'
            client_command = '%s client' % self.prog_name
            server = subprocess.Popen(server_command, shell=True)
            print 'server pid: %s' % server.pid
            time.sleep(5)
            clients = []
            for i in range(0, self.options.num_processes):
                client = subprocess.Popen(client_command, shell=True)
                clients.append(client)
            print 'waiting for clients to finish'
            for client in clients:
                client.wait()
            os.kill(server.pid, signal.SIGTERM)
        elif len(self.args) == 1:
            self.command = self.args[0]
            if hasattr(self, 'do_%s' % self.command):
                method = getattr(self, 'do_%s' % self.command)
                method()
            else:
                self.parser.error('command (%s) not recognized' % self.command)
        else:
            self.parser.error('unrecognized commands')
            
if __name__ == "__main__":
    delete = Delete()
    delete.main()
